﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class TankHealth1 : MonoBehaviour
{
    public float m_StartHealth = 100f;
    public Color m_HealthColor = Color.green;
    public Color m_DeathColor = Color.red;
    public GameObject m_ExplosivePrefab;
    public Slider m_HealthSlider;
    public Image m_HealthImage;


    private float m_CurrentHealth;
    private ParticleSystem m_ExplosivePartical;
    private AudioSource m_ExplosiveAudio;
    private bool m_isDead;

    private void Awake()
    {
        m_ExplosivePartical = Instantiate(m_ExplosivePrefab).GetComponent<ParticleSystem>();
        m_ExplosiveAudio = m_ExplosivePartical.GetComponent<AudioSource>();

        m_ExplosivePrefab.SetActive(false);
    }

    private void OnEnable()
    {
        m_CurrentHealth = m_StartHealth;
        m_isDead = false;
        UpdataHealthUI();
    }

    public void TakeDamage(float damage)
    {
        m_CurrentHealth -= damage;
        UpdataHealthUI();
        if (m_CurrentHealth < 0 && !m_isDead)
        {
            SetDeath();
        }
    }

    void UpdataHealthUI()
    {
        m_HealthSlider.value = m_CurrentHealth;
        m_HealthImage.color = Color.Lerp(m_DeathColor, m_HealthColor, m_CurrentHealth / m_StartHealth);
    }

    void SetDeath()
    {
        m_isDead = true;

        m_ExplosivePrefab.transform.position = transform.position;
        m_ExplosivePrefab.SetActive(true);

        m_ExplosivePartical.Play();
        m_ExplosiveAudio.Play();

        gameObject.SetActive(false);
        Debug.Log("SetDeath");
    }
}
